package com.sjjy.ta.impl;

import com.sjjy.ta.iface.MailInfoService;
import com.sys.plat.service.base.BaseServiceImpl;
import com.sys.tool.HttpClientTool;
import com.sys.tool.StringTool;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: mabo
 * Date: 11-3-11
 * Time: 下午8:22
 * To change this template use File | Settings | File Templates.
 */
public class MailInfoImpl extends BaseServiceImpl implements MailInfoService {
    public List mailList(String user_Id) {
        Session session = dao.getHibernateTemplate().getSessionFactory().openSession();
        Transaction t = session.beginTransaction();
        SQLQuery sq = session.createSQLQuery(
                "select *, 'in' AS `type` from in_mail  where in_mail.user_id = '" + user_Id + "' \n" +
                        "union\n" +
                        "select *,'out' AS `type` from out_mail  where  out_mail.user_Id = '" + user_Id + "'\n" +
                        "order by user_id, mailDate desc");

        t.begin();
        List list = sq.list();
        t.commit();
        session.close();
        return list;  //To change body of implemented methods use File | Settings | File Templates.
    }

    HttpClientTool hct = new HttpClientTool();

    public List postMail(String[] userId, Map data) {
        List retList = new ArrayList();


        sjjyLogin();

        List uIdList = new ArrayList();
        for (String uId : userId) {
            if (!(data.get("pass") != null && data.get("pass").equals("True"))) {
                if (this.dao.listByHql("FROM OutMail WHERE userId = ?", uId).size() > 0) {
                    retList.add(uId + " 已经为此用户发送过邮件");
                } else {
                    uIdList.add(uId);
                }
            }
        }

        List<String[]> uHash = new ArrayList<String[]>();
        for (Object uId : uIdList) {
            String uidhash = getUserHashByID(uId.toString());
            if (uidhash.equals("")) {
                retList.add(uId + " uidhash获取失败");
                continue;
            }
            uHash.add(new String[]{uId.toString(),uidhash});
        }

        for (int i = 0; i < uHash.size(); i++) {
            String[] h = uHash.get(i);
            postMail(h[0],h[1], data.get("doc").toString());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        }

        return retList;
    }

    public int postMail(String userId, Map data) {

        if (!(data.get("pass") != null && data.get("pass").equals("True"))) {
            if (this.dao.listByHql("FROM OutMail WHERE userId = ?", userId).size() > 0) {
                //已经发送过邮件
                return 3;
            }
        }

        sjjyLogin();

        String uidhash = getUserHashByID(userId);

        if (uidhash.equals("")) {
            return 2;
        }

        postMail(userId,uidhash, data.get("doc").toString());

        return 1;
    }


    private void sjjyLogin() {
        hct.setUrl("http://www.jiayuan.com/login/dologin.php?pre_url=/usercp&name=mabo%40ccapp.net&password=111222&remem_pass=on&ljg_login=1");
        hct.getInnerHTML();
    }

    private void postMail(String uid,String uidHash, String doc) {
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        list.add(new BasicNameValuePair("contents", doc));
        list.add(new BasicNameValuePair("is_saved", "1"));
        list.add(new BasicNameValuePair("to_hash", uidHash));


        list.add(new BasicNameValuePair("pre_url", "http://www.jiayuan.com/"+uid));
        list.add(new BasicNameValuePair("reply_msgid", "0"));
        list.add(new BasicNameValuePair("jifen", "0"));
        list.add(new BasicNameValuePair("reply_send_time", "0"));
        list.add(new BasicNameValuePair("self_pay", "0"));
        list.add(new BasicNameValuePair("fxbc", "0"));
        list.add(new BasicNameValuePair("pro_id", "0"));
        list.add(new BasicNameValuePair("is_saved", "1"));
        list.add(new BasicNameValuePair("now_draft_id", "0"));

        list.add(new BasicNameValuePair("mailtop", "on"));

        list.add(new BasicNameValuePair("ok_xinzhi_id", "01"));
        list.add(new BasicNameValuePair("read", "on"));

        list.add(new BasicNameValuePair("tmp_wenzi", "蓝天白云"));
        list.add(new BasicNameValuePair("tmp_xinzhi", "1"));

        hct.post("http://www.jiayuan.com/msg/dosend.php", list);
    }

    private String getUserHashByID(String userId) {

        hct.setUrl("http://www.jiayuan.com/" + userId);
        String html = hct.getInnerHTML();

        String uidhash = "";

        StringTool st = new StringTool();
        st.setMatcher(html);
        st.setPattern("uidhash=(.*?)\"");
        if (st.isFind()) {
            uidhash = st.getValue(1);
        } else {
            return "";
        }

        return uidhash;
    }
}
